<template>
  <div class="app-container flex column">
    <top-title :updateTime="true" :content="content"></top-title>
    <div class="content-wrap f1">
      <div class="tree-from-wrap f1 flex" style="height: 100%">
        <div class="left-tree f1 flex column">
          <!-- 按钮 -->
          <div class="btn-group flex">
            <div class="btn-common" @click="handleAdd(1)">添加下级</div>
            <!-- <div class="btn-common">批量删除</div> -->
          </div>

          <!-- 提醒 -->
          <div class="alter flex align-center">
            <img src="@/assets/imgs/system/alter_icon.png" alt="" />
            <span>当前选择:</span>
            <span v-if="currSelected.id">{{ currSelected.unitName }}</span>
            <span v-if="currSelected.id" @click="onClearSelected">取消选择</span>
          </div>

          <div class="search-group" style="padding: 0 0.1rem 0 0.2rem">
            <div class="input-wrap" style="width: 100%">
              <div class="input-item" style="padding: 0; width: 100%">
                <a-input v-model="value" @pressEnter="onSearch" :maxLength="15" placeholder="请输入区域名称">
                  <a-icon class="search-icon" slot="prefix" type="search" />
                  <a-button @click="onSearch" slot="suffix" type="primary" class="searchBtn" style="margin-right: 0">
                    搜索
                  </a-button>
                </a-input>
              </div>
            </div>
          </div>

          <div class="tree-wrap f1" style="height: 100%; padding: 0 0.2rem; overflow: scroll">
            <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
              <!-- <span style="user-select: none">
              <div class="tree-x" id="treeList" style="height: 100%; overflow: scroll"></div>
            </span> -->
              <a-tree
                multiple
                checkable
                :loading="loading"
                :selectedKeys="selectedKeys"
                :checkedKeys="checkedKeys"
                :treeData="departTree"
                :expandedKeys="iExpandedKeys"
                :checkStrictly="checkStrictly"
                :autoExpandParent="autoExpandParent"
                :replace-fields="replaceFields"
                @check="onCheck"
                @select="onSelect"
                @expand="onExpand"
                @rightClick="rightHandle"
              >
                <a-icon slot="switcherIcon" type="down" />
                <template #title="{ unitName }">
                  <span v-if="unitName.indexOf(value) > -1">
                    {{ unitName.substr(0, unitName.indexOf(value)) }}
                    <span style="color: #8beff2; background: #017f82">{{ value }}</span>
                    {{ unitName.substr(unitName.indexOf(value) + value.length) }}
                  </span>
                  <span v-else>{{ unitName }}</span>
                </template>
              </a-tree>
              <!--新增右键点击事件,和增加添加和删除功能-->
              <a-menu slot="overlay">
                <a-menu-item @click="handleAdd(2)" key="1">添加</a-menu-item>
                <a-menu-item @click="handleDelete" key="2">删除</a-menu-item>
                <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
              </a-menu>
            </a-dropdown>

            <div class="drawer-bootom-button">
              <a-dropdown :trigger="['click']" placement="topCenter">
                <a-menu class="much" slot="overlay">
                  <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
                  <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
                  <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
                  <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
                  <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
                  <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
                </a-menu>
                <a-button class="searchBtn">
                  树操作
                  <a-icon type="up" />
                </a-button>
              </a-dropdown>
            </div>
          </div>
        </div>

        <div class="right-form f1">
          <a-card class="right-form-wrapper" :bordered="false" v-if="selectedKeys.length > 0">
            <a-form-model :model="form" ref="form" class="formStyle" autocomplete="off" layout="inline" :rules="rules">
              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-model-item label="单位名称" prop="unitName">
                    <a-input placeholder="请输入区域名称" v-model.trim="form.unitName" />
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-model-item label="上级机关" prop="parentName">
                    <a-input placeholder="请选择上级区域" v-model.trim="form.parentName" :disabled="true" />
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row :gutter="24" v-if="record.type == 2">
                <a-col :span="24">
                  <a-form-model-item label="选择区县" prop="regionId">
                    <a-select ref="select" v-model="regionId" style="width: 100%" placeholder="请选择区县">
                      <a-select-option v-for="(item, index) in regionIdList" :key="index" :value="item.id">
                        {{ item.regionName }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row :gutter="24" v-if="record.type == 3">
                <a-col :span="24">
                  <a-form-model-item label="管辖街道">
                    <a-checkbox-group v-model="checkboxRegionIdList">
                      <a-checkbox :key="index" :value="item.id" v-for="(item, index) in regionIdList">
                        {{ item.regionName }}
                      </a-checkbox>
                    </a-checkbox-group>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row :gutter="4">
                <a-col :span="22">
                  <a-form-model-item label="经度">
                    <a-input placeholder="例如104.123456" v-model.trim="form.lat" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="2">
                  <img
                    @click="showMap"
                    class="select-map-img cursor"
                    style="width: 36px; height: 36px"
                    src="@/assets/imgs/system/in-map.png"
                  />
                </a-col>
              </a-row>

              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-model-item label="纬度">
                    <a-input placeholder="例如34.865432" v-model.trim="form.lng" />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>

            <div class="anty-form-btn flex justify-center">
              <a-button @click="emptyCurrForm" class="resetBtn" type="primary" htmlType="button" icon="sync">
                重置
              </a-button>
              <a-button
                @click="submitCurrForm"
                class="searchBtn"
                type="primary"
                htmlType="button"
                icon="form"
                style="margin-left: 40px"
              >
                保存
              </a-button>
            </div>
          </a-card>

          <a-card :bordered="false" v-else>
            <a-empty>
              <span slot="description">请先选择一个区域!</span>
            </a-empty>
          </a-card>
        </div>
      </div>
    </div>

    <depart-modal ref="departModal" @ok="loadTree"></depart-modal>
    <a-map :visible.sync="isShowMap" @border="getBorder" @getLatLong="getLatLong" ref="aMap"></a-map>
  </div>
</template>

<script>
import topTitle from '@/components/topTitle'
import departModal from './modules/departModal'
import AMap from '@/components/a-map/index.vue'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { comMethods } from '@/mixins/comMethods'
import { httpAction, deleteAction, getAction } from '@/api/manage'
import { unitTreeList, unitEdit, unitDel } from '@/api/api'
export default {
  name: 'district',
  mixins: [JeecgListMixin, comMethods],
  components: { topTitle, AMap, departModal },
  data() {
    // let vaildUserId = (rule, value, callback) => {
    //   if ((value === '' || !value) && this.checkboxRegionIdList.length) {
    //     callback(new Error('请勾选管辖街道'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      content: [['单位管理']],
      loading: false,
      value: '', // tree search value
      dataList: [],
      dropTrigger: '',
      selectedKeys: [],
      checkedKeys: [],
      departTree: [],
      iExpandedKeys: [],
      checkStrictly: true,
      replaceFields: {
        key: 'id',
        title: 'unitName',
      },
      autoExpandParent: true,
      disableMixinCreated: true,
      currSelected: {},
      url: {
        edit: '/sys/police_agency/edit',
        exportXlsUrl: 'sys/sysDepart/exportXls',
        importExcelUrl: '/sys/sysDepart/importExcel',
      },
      // 右边

      form: {},
      rules: {
        unitName: [{ required: true, message: '请输入单位名称!' }],
        parentName: [{ required: true, message: '请选择上级区域名称!' }],
        lng: [{ required: true, message: '请输入纬度!' }],
        lat: [{ required: true, message: '请输入经度!' }],
      },
      regionId: '',
      regionIdList: [],
      checkboxRegionIdList: [],
      publicVisible: false,
      imageUrl: [],
      fileList: [],
      showUploadList: {
        showPreviewIcon: false,
      },
      isShowMap: false,
      imgPrefix: '',
    }
  },
  mounted() {
    this.loadTree()
  },
  methods: {
    onSearch() {
      const expanded = this.dataList
        .map((item) => {
          if (item.unitName.indexOf(this.value) > -1) {
            return this.getParentKey(item.id, this.departTree)
          }
          return null
        })
        .filter((item, i, self) => {
          if (item && self.indexOf(item) === i) {
            return item
          }
        })
      this.expandedKeys = expanded
      this.autoExpandParent = true
    },

    getParentKey(key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.id === key)) {
            parentKey = node.id
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },

    generateList(tree) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        const id = node.id
        const unitName = node.unitName
        this.dataList.push({
          id,
          unitName,
        })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },

    loadTree() {
      this.loading = true
      unitTreeList().then((res) => {
        this.treeData = []
        this.departTree = []
        if (res.code == 200) {
          this.allTreeKeys = []
          this.treeData.push(res.result[0])
          this.departTree.push(res.result[0])
          // this.setThisExpandedKeys(res.result[0])
          this.getAllKeys(res.result[0]) // * 用于右下角树操作功能
          this.generateList(this.departTree) // * 用作搜索 书中包含关键字的方法
          this.loading = false
        }
      })
    },

    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },

    getAllKeys(node) {
      // * 用于右下角树操作功能
      this.allTreeKeys.push(node.id)
      if (node.children && node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          this.getAllKeys(node.children[a])
        }
      }
    },

    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },

    onCheck(checkedKeys, info) {
      // this.imageUrl = []
      // this.fileList = []
      let record = info.node.dataRef
      console.log('onCheck-record', record)
      this.currSelected = Object.assign({}, record)
      this.selectedKeys = [record.id]
      if (this.checkStrictly) {
        this.checkedKeys = checkedKeys.checked
      } else {
        this.checkedKeys = checkedKeys
      }
      this.setValuesToForm(record)
    },

    onSelect(selectedKeys, e) {
      // this.imageUrl = []
      // this.fileList = []
      let record = e.node.dataRef
      console.log('onSelect-record', record)
      this.currSelected = Object.assign({}, record)
      this.checkedKeys = [record.id] // ! 设置勾选
      this.selectedKeys = [record.id]
      console.log(this.selectedKeys, 'selectedKeys')
      this.setValuesToForm(record)
    },

    // 触发onSelect事件时,为区域树右侧的form表单赋值
    async setValuesToForm(record) {
      this.record = record
      this.form = { ...record }
      this.form.parentName = this.getNodeById(this.treeData, record.parentId).unitName
      await this.getTargetInitList(record.parentId)
      await this.getTargetRegionList(record.id)
    },

    async getTargetInitList(unitId) {
      let { result } = await getAction('/sys/region/find_sub_region_list', { unitId })
      this.regionIdList = result
      console.log(this.regionIdList, 'this.regionIdList')
    },
    async getTargetRegionList(unitId) {
      let { result } = await getAction('/sys/region/find_bind_region_list', { unitId })
      let checkRegionIdList = result.map((item) => {
        return item.id
      })
      if (this.record.type == 2) this.regionId = checkRegionIdList[0]
      else if (this.record.type == 3) this.checkboxRegionIdList = checkRegionIdList
      console.log(this.form.regionIdList, 'this.form.regionIdList')
    },

    getNodeById(list, id) {
      if (id == '' || id == null) return { unitName: '暂无' }
      for (const item of list) {
        if (item.id === id) return item
        if (item.children) {
          const res = this.getNodeById(item.children, id)
          if (res) return res
        }
      }
    },

    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },

    closeDrop() {
      // ! 右键店家下拉关闭下拉框
      this.dropTrigger = ''
    },

    rightHandle(node) {
      // ! 右键操作方法
      console.log(node.node, 'rightHandle')
      this.dropTrigger = 'contextmenu'
      this.rightClickSelectedKey = node.node.eventKey
      this.rightClickSelectedRegionName = node.node.dataRef.unitName
    },

    handleAdd(num) {
      if (num == 2) {
        // 右键添加
        if (this.getNodeById(this.treeData, this.rightClickSelectedKey).type == 3) {
          this.$message.error('已经是最子集了,不支持再添加')
          return
        }
        this.$refs.departModal.add({
          parentId: this.rightClickSelectedKey,
          parentName: this.rightClickSelectedRegionName,
          type: this.record.type,
        })
      } else {
        // 按键添加
        if (this.getNodeById(this.treeData, this.selectedKeys[0]).type == 3) {
          this.$message.error('已经是最子集了,不支持再添加')
          return
        }
        let parentId = this.currSelected.id
        let parentName = this.currSelected.unitName
        if (!parentId) {
          this.$message.warning('请先点击选中上级区域！')
          return false
        }
        this.$refs.departModal.add({ parentId, parentName, type: this.record.type })
      }
    },

    handleDelete() {
      this.$confirm({
        title: '确认删除',
        content: '确定要删除此区域以及子节点数据吗?',
        onOk: () => {
          unitDel({ id: this.rightClickSelectedKey }).then((resp) => {
            if (resp.code == 200) {
              //删除成功后，去除已选中中的数据
              this.form = {}
              this.imageUrl = []
              this.fileList = []
              this.checkedKeys.splice(
                this.checkedKeys.findIndex((key) => key === this.rightClickSelectedKey),
                1,
              )
              this.$message.success('删除成功!')
              this.loadTree()
              //删除后同步清空右侧基本信息内容
              let orgCode = this.form.getFieldValue('orgCode')
              if (orgCode && orgCode === this.rightClickSelectedOrgCode) {
                this.onClearSelected()
              }
            } else {
              this.$message.warning('删除失败!')
            }
          })
        },
      })
    },

    onClearSelected() {
      // ! 清空方法
      this.checkedKeys = []
      this.currSelected = {}
      this.form = {}
      this.regionId = ''
      this.checkboxRegionIdList = []
      this.selectedKeys = []
    },

    // * 右下角 dropdown 功能开始
    switchCheckStrictly(v) {
      if (v == 1) {
        this.checkStrictly = false
      } else if (v == 2) {
        this.checkStrictly = true
      }
    },
    checkALL() {
      this.checkStriccheckStrictlytly = false
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      this.checkedKeys = []
    },
    expandAll() {
      this.iExpandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.iExpandedKeys = []
    },
    // * 右下角 dropdown 功能结束

    // ! 表单上传图片方法

    remove(file) {
      let uid = file.uid
      let index = this.fileList.findIndex((v) => {
        return v.uid == uid
      })
      this.fileList.splice(index, 1)
      this.imageUrl.splice(index, 1)
    },

    async customRequest(info) {
      const isJpgOrPng =
        info.file.type === 'image/jpeg' || info.file.type === 'image/png' || info.file.type === 'image/jpg'
      if (!isJpgOrPng) {
        this.$message.error('只能上传jpg，png，jpeg格式图片!')
        return
      }

      this.isLt2M = info.file.size / 1024 / 1024 < 2
      if (!this.isLt2M) {
        this.$message.warn('请上传小于200KB的照片!')
      }

      if (isJpgOrPng && this.isLt2M) {
        let file = info.file
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', 13)
        let res = await uploadFile(formData)
        if (res.code == 200) {
          this.imageUrl.push(res.result.halfPath)
        }
      }
    },
    uploadChange({ file, fileList }) {
      if (this.isLt2M) {
        file.status = 'done'
        this.fileList = fileList
      }
    },

    // ! 地图方法开始
    showMap() {
      this.isShowMap = true
    },
    getLatLong(value) {
      this.form.lat = value[0]
      this.form.lng = value[1]
    },
    getBorder(value) {
      this.form.areaPosition = value
    },
    createBorderLine() {
      this.$refs.aMap.borderLine = true
      this.isShowMap = true
    },
    // ! 地图方法结束

    // ! 右侧表单的事件
    emptyCurrForm() {
      this.form = {}
      // this.selectedKeys = []
    },
    submitCurrForm() {
      console.log(this.form)
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        if (this.form.lat == null || this.form.lat == '') {
          this.$message.error('经度不能为空,请选择经维度')
          return
        }
        if (this.form.lng == null || this.form.lng == '') {
          this.$message.error('纬度不能为空,请选择经维度')
          return
        }
        if (!this.currSelected.id) {
          this.$message.warning('请点击选择要修改区域!')
          return
        }
        if (this.record.type == 2) {
          let regionIdList = []
          regionIdList.push(this.regionId)
          this.form.regionIdList = regionIdList
        } else if (this.record.type == 3) {
          this.form.regionIdList = this.checkboxRegionIdList
        }
        unitEdit(this.form).then((res) => {
          if (res.code == 200) {
            this.$message.success('保存成功!')
            this.loadTree()
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
  },
  destroy() {},
}
</script>

<style scoped lang="less">
/deep/ .ant-form-item-control-wrapper {
  overflow: auto;
}
/deep/ .ant-card {
  background: #045053;
  color: #00f8ff;
}
/deep/ .ant-checkbox-wrapper {
  color: #017f82;
}
/deep/ .ant-checkbox-checked::after {
  border: 1px solid #036265;
}
/deep/ .ant-checkbox-inner {
  background-color: #036265;
  border-color: #036265;
}
/deep/ .ant-checkbox-checked {
  background: transparent !important;
  color: #9cfdff !important;
}

/deep/ .ant-checkbox-wrapper:hover .ant-checkbox-inner,
.ant-checkbox:hover .ant-checkbox-inner,
.ant-checkbox-input:focus + .ant-checkbox-inner {
  border-color: #036265;
}

.app-container {
  .left-tree {
    position: relative;
    background: #045053;

    .btn-group {
      padding: 0.2rem 0 0 0.2rem;
      .btn-common {
        width: 1.2rem;
        height: 0.4rem;
        line-height: 0.4rem;
        text-align: center;
        background: #00f8ff;
        border-radius: 0.04rem;
        font-size: 0.16rem;
        font-weight: bold;
        color: #023234;
        cursor: pointer;
        &:nth-child(2) {
          margin-left: 0.2rem;
        }
      }
    }

    .drawer-bootom-button {
      position: absolute;
      right: 0.1rem;
      bottom: 0.1rem;
      border-radius: 0.04rem;
    }
  }

  .right-form {
    background: #003a39;
    margin-left: 0.2rem;

    .right-form-wrapper {
      height: 100%;
      // height: 8rem;
      // overflow-y: auto;
    }
  }
}
</style>
